package com.chx.three.mama.utils;

/**
 * Created by Casio on 2015/2/5.
 */

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Set;

/**
 * HTTP网络请求的工具类，包含了GET,POST,PUT,DELETE,以及检查网络连接
 * 这四种请求方法的支持
 */
public class HttpTool {

    //GET请求

    /**
     * 执行GET请求
     * @param url 请求的网址
     * @return byte[] 网络数据
     */
    public static byte[] get(String url){

        byte[] ret = null;
        if (url!=null){

            HttpGet request=new HttpGet(url);
            ret = processDirectoryRequest(request);
        }
        return ret;

    }


    public static byte[] delete(String url){

        byte[] ret=null;
        if (url!=null){

            HttpDelete request = new HttpDelete(url);
            ret = processDirectoryRequest(request);
        }
        return ret;
    }


    public static byte[] processDirectoryRequest(HttpRequestBase request){

        byte[] ret=null;

            DefaultHttpClient client = new DefaultHttpClient();
            try {
                HttpResponse response = client.execute(request);
                StatusLine statusLine = response.getStatusLine();
                if (statusLine.getStatusCode()==200){

                    HttpEntity entity = response.getEntity();
                    ret = EntityUtils.toByteArray(entity);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        return ret;

    }



    /**
     * 执行POST请求。
     * POST请求要提交数据，提交数据的方式，本方法采用提交 key=value & key=value 的形式
     * 这种数据格式就是网页中，form 表单提交的数据格式
     * @param url 请求的网址
     * @param params HashMap柏寒的参数，也就是 key=value 的集合。
     * @return
     */
    public static byte[] post(String url, HashMap<String,String> params){
        return post(url,params,"UTF-8");
    }



    public static byte[] post(String url, HashMap<String,String> params,String encoding){
        byte[] ret = null;
        if (url!=null){

            HttpPost request=new HttpPost(url);
            //用于设置提价的数据,对于 key=value & key=value 的形式，需要使用
            //UrlEncodedFormEntity
            ret=processEntityRequest(request,params,encoding);
        }
        return ret;
    }


    public static byte[] put(String url,HashMap<String,String> params,String encoding){

        byte[] ret=null;
        if (url!=null){

            HttpPut request = new HttpPut(url);
            ret=processEntityRequest(request,params,encoding);
        }
        return ret;
    }

    /**
     * 本方法实现了 POST请求与PUT请求，发送key=value形式参数的通用代码
     * @param request
     * @param params
     * @param encoding
     * @return
     */

    private static byte[] processEntityRequest(
                                               HttpEntityEnclosingRequestBase request,
                                               HashMap<String,String> params,
                                               String encoding){
        byte[] ret=null;

        if (request!=null) {
            if (params!=null) {
                try {
                    LinkedList<NameValuePair> nameValuePairs = new LinkedList<NameValuePair>();
                    Set<String> keySet = params.keySet();
                    for (String key : keySet) {

                        String value = params.get(key);
                        nameValuePairs.add(new BasicNameValuePair(key, value));
                    }

                    if (encoding == null)
                        encoding = "UTF-8";

                    UrlEncodedFormEntity entity =
                            new UrlEncodedFormEntity(nameValuePairs, encoding);
                    request.setEntity(entity);

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }

            HttpClient client = new DefaultHttpClient();
            try {
                HttpResponse response = client.execute(request);
                StatusLine statusLine = response.getStatusLine();
                if (statusLine.getStatusCode() == 200) {

                    HttpEntity entity = response.getEntity();
                    ret = EntityUtils.toByteArray(entity);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return ret;
    }



    public static boolean isNetworkAvailable(Context context){

        ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(
                Context.CONNECTIVITY_SERVICE);

        if(connectivity == null){
            return false;
        }else {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if(info != null ){
                for(int i=0; i<info.length; i++){
                    if(info[i].getState() == NetworkInfo.State.CONNECTED){
                        return true;
                    }
                }
            }
        }
        return false;
    }



    public static void checkhttp(final Activity activity){
        if(!isNetworkAvailable(activity)){
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle("网络错误，请检查网络设置");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    activity.finish();
                }
            });
            builder.show();
        }else {
            //这儿主要是用来测试的，实际中没有必要...
            Toast.makeText(activity, "网络正常", Toast.LENGTH_LONG).show();
        }
    }
}
